package com.ouc.pampas;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;

import com.ouc.openplatform.pampas.SessionManager;
@SuppressWarnings("deprecation")
public class ClusterHttpSessionWrapper implements HttpSession {
	private SessionManager sessionService;
	private Map<Object, Object> map;
	private String sessionId;
	private long creationTime;
	private long lastAccessedTime;
	private int maxInactiveInterval;
	private ServletContext servletContext;
	private boolean isNew = false;
	private boolean changed;

	public ClusterHttpSessionWrapper(String sessionId, ServletContext servletContext, SessionManager sessionService) {
		this.sessionId = sessionId;
		this.sessionService = sessionService;
		this.map = this.sessionService.getSession(sessionId);
		this.creationTime = ((Long) this.map.get("_SESSION_CREATE_TIME_")).longValue();
		this.lastAccessedTime = System.currentTimeMillis();
		this.servletContext = servletContext;
		this.isNew = true;
	}

	public Object getAttribute(String key) {
		resetLastAccessTime();
		return this.map.get(key);
	}

	public void invalidate() {
		resetLastAccessTime();
		this.map.clear();
		this.map.put("_SESSION_CREATE_TIME_", Long.valueOf(System.currentTimeMillis()));
		this.changed = true;
		this.sessionService.removeSession(this.sessionId);
	}

	public void removeAttribute(String key) {
		resetLastAccessTime();
		this.map.remove(key);
		this.changed = true;
	}

	public void setAttribute(String key, Object value) {
		resetLastAccessTime();
		this.map.put(key, value);
		this.changed = true;
	}

	public String getId() {
		return this.sessionId;
	}

	public void saveSession() {
		if (this.changed) {
			this.sessionService.updateSession(this.sessionId, this.map);
		}
	}

	public long getCreationTime() {
		return this.creationTime;
	}

	public long getLastAccessedTime() {
		return this.lastAccessedTime;
	}

	private void resetLastAccessTime() {
		this.lastAccessedTime = System.currentTimeMillis();
		this.map.put("_SESSION_CREATE_TIME_", Long.valueOf(this.lastAccessedTime));
	}

	public void setMaxInactiveInterval(int interval) {
		this.maxInactiveInterval = interval;
	}

	public int getMaxInactiveInterval() {
		return this.maxInactiveInterval;
	}

	public ServletContext getServletContext() {
		return this.servletContext;
	}

	
	public Object getValue(String name) {
		return getAttribute(name);
	}

	

	public void putValue(String name, Object value) {
		setAttribute(name, value);
	}

	public void removeValue(String name) {
		removeAttribute(name);
	}

	public boolean isNew() {
		return this.isNew;
	}

	@Override
	public Enumeration<String> getAttributeNames() {
		return null;
	}

	@Override
	public HttpSessionContext getSessionContext() {
		return null;
	}

	@Override
	public String[] getValueNames() {
		return null;
	}
}
